package io.github.frailty9.crserver.controller

import cn.dev33.satoken.stp.StpUtil
import cn.dev33.satoken.util.SaResult
import io.github.frailty9.crserver.dso.service.ReservationService
import io.github.frailty9.crserver.dso.service.ResourceInstanceService
import io.github.frailty9.crserver.dso.service.ResourceService
import io.github.frailty9.crserver.dto.ResourceBookingParam
import io.github.frailty9.crserver.dto.ResourcePublishDto
import mu.KotlinLogging
import org.noear.solon.annotation.Controller
import org.noear.solon.annotation.Inject
import org.noear.solon.annotation.Mapping
import org.noear.solon.annotation.Path
import org.noear.solon.web.cors.annotation.CrossOrigin

@Suppress("unused")
@CrossOrigin(origins = "*")
@Controller
@Mapping("/api/resource")
class ResourceController {

    @Inject
    private lateinit var resourceService: ResourceService

    @Inject
    private lateinit var riService: ResourceInstanceService

    @Inject
    private lateinit var reservationService: ReservationService

    private val log = KotlinLogging.logger { }

    @Mapping("/publish")
    fun publish(resourcePublishDto: ResourcePublishDto): SaResult {
        log.debug { resourcePublishDto }
        val userId = StpUtil.getLoginIdAsLong()
        resourceService.publish(userId, resourcePublishDto)
        return SaResult.ok()
    }

    @Mapping("/list")
    fun list(current: Long?, size: Long?): SaResult {
        val result = resourceService.getActiveResourceDtoPage(current ?: 1L, size ?: 10L)
        return SaResult.data(result)
    }

    @Mapping("/detail/{id}")
    fun resourceDetail(@Path id: Long): SaResult {
        val resource = resourceService.getById(id)
        return if (resource != null)
            SaResult.data(resource)
        else
            SaResult.error("资源不存在")
    }

    @Mapping("/instances/{rid}")
    fun getById(rid: Long): SaResult {
        val instances = riService.getResourceInstances(rid)
        return SaResult.data(instances)
    }

    @Mapping("/instance/detail/{instanceId}")
    fun instanceDetail(@Path instanceId: Long): SaResult {
        val instance = riService.getById(instanceId)
        return if (instance != null)
            SaResult.data(instance)
        else
            SaResult.error("实例不存在")
    }
}
